using imitateMacQQ.WebApi.Configures;
using imitateMacQQ.WebApi.Domain.Modifying_User_Information.Entity;
using imitateMacQQ.WebApi.Domain.Modifying_User_Information.Interface;
using imitateMacQQ.WebApi.Domain.Request.utils;
using imitateMacQQ.WebApi.Repository.EFCore.Model;
using Microsoft.EntityFrameworkCore;

namespace imitateMacQQ.WebApi.Domain.Modifying_User_Information.Service;

public class UserInfoService : IUserInfoService
{
    private readonly INLogHelper _logHelper;

    public UserInfoService(INLogHelper logHelper)
    {
        _logHelper = logHelper;
    }

    public async Task<Request<bool>> AlterMyselfInfo(UserInfoMap dto)
    {
        try
        {
            await using var db = new DataDbContext();//修改个人信息
            var usr = await db.Users.FirstOrDefaultAsync(e =>
                e.Account == dto.Account);
            if (usr is null)
                throw new Exception("Bad Request! Not Find User");
            usr.Password = dto.Password;
            usr.Live = dto.Live;
            usr.UserName = dto.UserName;
            usr.Sex = dto.Sex;
            usr.Show = dto.Show;
            usr.Intro = dto.Intro;
            usr.Show = dto.Show;
            await db.SaveChangesAsync();
            return Request<bool>.Ok(true);
        }
        catch (Exception ex)
        {
            _logHelper.LogError(ex);
            return Request<bool>.Ok(false, false, "BadRequest");
        }
    }

    public async Task<Request<UserInfoMap>> GetMyselfInfo(string account)
    {
        try
        {
            await using var db = new DataDbContext();//获取个人信息
            var info = await db.Users.FirstOrDefaultAsync(e => e.Account == account);
            if (info is null)
                throw new Exception("User Table is Bad! => NOT Find This UserInfo");
            return Request<UserInfoMap>.Ok(new UserInfoMap()
            {
                Account = info.Account,
                UserName = info.UserName,
                Password = info.Password,
                Sex = info.Sex,
                Birthday = info.Birthday,
                Header = info.Header,
                Intro = info.Intro,
                Live = info.Live,
                Show = info.Show
            });
        }
        catch (Exception ex)
        {
            _logHelper.LogError(ex);
            return Request<UserInfoMap>.Ok(null!);
        }
    }
}